package com.king.config;

import com.king.pojo.Configuration;
import com.king.pojo.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @ClassName: XMLMapperBuilder
 * @Description: 解析Mapper
 * @Author: wangchangyong
 * @Date: 2020/3/26 21:06
 * @Version: 1.0.0
 **/
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException {

        Document document = new SAXReader().read(in);

        // mapper
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        // select
        List<Element> selectList = rootElement.selectNodes("//select");
        for (Element element : selectList) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();

            MapperStatement mapperStatement = new MapperStatement();
            mapperStatement.setId(id);
            mapperStatement.setResultType(resultType);
            mapperStatement.setParameterType(parameterType);
            mapperStatement.setSql(sql);
            configuration.getMapperStatementMap().put(namespace + "." + id, mapperStatement);
        }

        // insert|delete|update
        List<Element> insertList = rootElement.selectNodes("//insert|//delete|//update");
        for (Element element : insertList) {
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();

            MapperStatement mapperStatement = new MapperStatement();
            mapperStatement.setId(id);
            mapperStatement.setParameterType(parameterType);
            mapperStatement.setSql(sql);
            configuration.getMapperStatementMap().put(namespace + "." + id, mapperStatement);
        }

    }
}
